package p.ithorns.integration.hazelcast.serialization;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hazelcast.nio.serialization.compact.CompactReader;
import com.hazelcast.nio.serialization.compact.CompactSerializer;
import com.hazelcast.nio.serialization.compact.CompactWriter;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.Serializable;

/**
 * MybatisPlusBaseMapperSerializer
 *
 * @author Ht.L
 * @date 2023-10-18 19:17
 * @since 1.0.0
 */
public class MybatisPlusBaseMapperSerializer implements CompactSerializer<BaseMapper>, Serializable {

    private SqlSessionFactory sqlSessionFactory;

    public MybatisPlusBaseMapperSerializer(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public BaseMapper read(CompactReader reader) {
        // 从 reader 中读取相关信息，并根据信息创建 BaseMapper 实例
        // 例如，你可以从 reader 中读取类名，并通过反射创建实例
        String className = reader.readString("className");
        try {
            Class<?> clazz = Class.forName(className);
            return (BaseMapper) sqlSessionFactory.openSession().getMapper(clazz);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Failed to read BaseMapper.", e);
        }
    }

    @Override
    public String getTypeName() {
        return BaseMapper.class.getSimpleName();
    }

    @Override
    public Class<BaseMapper> getCompactClass() {
        return BaseMapper.class;
    }

    @Override
    public void write( CompactWriter writer, BaseMapper object) {
        // 将 object 的相关信息写入 writer
        // 例如，你可以将 object 的类名写入
        String className = object.getClass().getName();
        writer.writeString("className", className);
    }
}